package mamikeji.liaowa.application;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Typeface;
import android.os.Handler;
import android.support.multidex.MultiDex;

import com.facebook.drawee.backends.pipeline.Fresco;
import com.squareup.leakcanary.RefWatcher;
import com.tencent.smtt.sdk.QbSdk;
import com.umeng.analytics.MobclickAgent;
import com.umeng.socialize.Config;
import com.umeng.socialize.PlatformConfig;
import com.umeng.socialize.UMShareAPI;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import cn.jpush.android.api.JPushInterface;
import mamikeji.liaowa.gen.DaoMaster;
import mamikeji.liaowa.gen.DaoSession;

/**
 * application
 */
public class MyApplication extends Application {
    //获取屏幕的高，宽
    public static float screenHeight, screenWidth;
    //    private SQLHelper sqlHelper;
    private static Handler mainHandler;//全局的主线程的handler
    private List<Activity> activities = new ArrayList<Activity>();
    /**
     * bajiebaoapp对象
     */
    private static MyApplication instance = null;

    public static Typeface TypeFaceYaHei;

    private DaoSession daoSession;

    {
        PlatformConfig.setWeixin("wxca3901d1edbdef5f", "8d7991ae7dd1eb6043ddf9d5abbc0943");
        PlatformConfig.setQQZone("1106264864", "kbFJpZxqBvhxk3wH");
    }

    //内存泄漏测试工具
    private RefWatcher mRefWatcher;

    @Override
    public void onCreate() {
        super.onCreate();

        Fresco.initialize(this);

        instance = this;
        //在主线程中new的handler就是主线程的handler
        mainHandler = new Handler();//初始化Handler
        screenHeight = getResources().getDisplayMetrics().heightPixels;
        screenWidth = getResources().getDisplayMetrics().widthPixels;

        JPushInterface.init(this);

        UMShareAPI.get(this);

        initGreenDao();

        //X5内核预加载
        initX5Code();

        MobclickAgent.openActivityDurationTrack(false);//友盟页面统计，按钮计数


        //内存泄漏
//        mRefWatcher = LeakCanary.install(this);
        //极光调试
        JPushInterface.setDebugMode(false);//正式版的时候设置false，关闭调试
        //友盟调试
        Config.DEBUG = false;
    }

    private void initX5Code() {
        //搜集本地tbs内核信息并上报服务器，服务器返回结果决定使用哪个内核。
        QbSdk.PreInitCallback cb = new QbSdk.PreInitCallback() {
            @Override
            public void onViewInitFinished(boolean arg0) {
                // TODO Auto-generated method stub
                //x5內核初始化完成的回调，为true表示x5内核加载成功，否则表示x5内核加载失败，会自动切换到系统内核。
            }

            @Override
            public void onCoreInitFinished() {
                // TODO Auto-generated method stub
            }
        };
        //x5内核初始化接口
        QbSdk.initX5Environment(getApplicationContext(), cb);
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }

    private void initGreenDao() {
        DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(this, "liaowa.db");
        SQLiteDatabase db = helper.getWritableDatabase();
        DaoMaster daoMaster = new DaoMaster(db);
        daoSession = daoMaster.newSession();
    }

    public DaoSession getDaoSession() {
        return daoSession;
    }

//    /**
//     * 获取数据库Helper
//     */
//    public SQLHelper getSQLHelper() {
//        if (sqlHelper == null)
//            sqlHelper = new SQLHelper(instance);
//        return sqlHelper;
//    }

    /**
     * 获得实例
     *
     * @return
     */
    public static MyApplication getInstance() {
        return instance;
    }


    /**
     * 把每个打开的activity放入activity列表中
     *
     * @param activity
     */
    public void addActivity(Activity activity) {
        activities.add(activity);
    }

    /**
     * 结束指定的Activity
     *
     * @param activity
     */
    public void closeActivity(Activity activity) {
        if (activity != null) {
            this.activities.remove(activity);
            activities.remove(activity);
            activity.finish();
            activity = null;
        }
    }

    /**
     * 应用退出，结束所有的activity
     */
    public void exit() {
        try {
            for (Activity activity : activities) {
                if (activity != null)
                    activity.finish();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            System.exit(0);
        }
    }


    /**
     * 设置全局字体
     */
    public void initTextType() {
        TypeFaceYaHei = Typeface.createFromAsset(getAssets(), "fonts/app_text_css.ttf");
        try {
            Field field = Typeface.class.getDeclaredField("MONOSPACE");
            field.setAccessible(true);
            field.set(null, TypeFaceYaHei);
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取context对象
     */
    public static Context getContext() {
        return instance.getApplicationContext();
    }

    /**
     * 获取全局的主线程的handler对象
     *
     * @return
     */
    public static Handler getMainHandler() {
        return mainHandler;
    }
}
